/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.bussiness.orderlang.order.controller;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONPath;
import com.google.gson.Gson;
import com.seeyoui.kensite.bussiness.orderlang.order.domain.Order;
import com.seeyoui.kensite.bussiness.orderlang.order.domain.OrderDTO;
import com.seeyoui.kensite.bussiness.orderlang.order.domain.OrderReportVO;
import com.seeyoui.kensite.bussiness.orderlang.order.domain.OrderStatisticsVO;
import com.seeyoui.kensite.bussiness.orderlang.order.domain.OrderVO;
import com.seeyoui.kensite.bussiness.orderlang.order.service.OrderService;
import com.seeyoui.kensite.bussiness.orderlang.orderProduct.domain.OrderProduct;
import com.seeyoui.kensite.bussiness.orderlang.orderProduct.service.OrderProductService;
import com.seeyoui.kensite.bussiness.orderlang.reject.domain.RejectReportVO;
import com.seeyoui.kensite.bussiness.orderlang.reject.domain.RejectStatisticsVO;
import com.seeyoui.kensite.bussiness.orderlang.reject.service.RejectService;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.Result;
import com.seeyoui.kensite.common.util.excel.ExportExcel;

/**
 * Order
 * 
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-02-07
 */

@Controller
@RequestMapping(value = "orderlang/order")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private RejectService rejectService;

    /**
     * 查询订单详情头部部分
     * 
     * @param modelMap
     * @param orderId
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:view")
    @RequestMapping(value = "/orderDetailForTitle", method = RequestMethod.POST)
    @ResponseBody
    public Object orderDetailForTitle(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, String orderId)
            throws Exception {
        Map map = new HashMap();
        map.put("orderId", orderId);
        Order order = orderService.findorderDetailForTitle(map);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", order);
        return dataMap;
    }

    /**
     * 展示列表页面
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:view")
    @RequestMapping(value = "/{page}")
    public ModelAndView view(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            @PathVariable String page) throws Exception {
        return new ModelAndView("bussiness/orderlang/order/" + page, modelMap);
    }

    @RequestMapping("/goOrderForm")
    public String goOrderForm() {
        return "bussiness/orderlang/distributor/order_form";
    }

    @RequestMapping("/goNewOrder")
    public String goNewOrder() {
        return "bussiness/orderlang/distributor/new_order";
    }

    /**
     * 查询数据集合,订单页面数据展示 多个条件查询
     * 
     * @param orderCode
     * @param startTime
     * @param endTime
     * @param customerName
     * @param orderState
     * @param paymentState
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/orderList", method = RequestMethod.POST)
    @ResponseBody
    public Result findAllListByCondition(String orderCode, String startTime, String endTime, String customerName, String orderState, int page,
            int rows, String paymentState, OrderDTO orderDTO) throws Exception {
        System.out.println("OrderController.findAllListByCondition()");
        List<OrderVO> orderList = orderService.findAllListByCondition(orderCode, startTime, endTime, /*
                                                                                                      * customerName
                                                                                                      * ,
                                                                                                      */orderState, paymentState, page, rows,
                orderDTO);
        int total = orderService.findTotal();
        Page<Order> pageInfo = new Page<Order>(page, rows, total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", orderList);
        dataMap.put("page", pageInfo);
        if (orderList.isEmpty()) {
            return Result.failure("查询失败");
        } else {
            return Result.success(dataMap);
        }
    }
    
    /**
     * 提交订单，保存订单及订单商品
     * @param orderMsg
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/saveOrderAndProduct", method = RequestMethod.POST)
    @ResponseBody
    public Result saveOrderAndProduct(String orderMsg) throws Exception{
    	// 去掉特殊字符
    	String orderInfo = StringEscapeUtils.unescapeHtml(orderMsg);
    	String date = (String) JSONPath.read(orderInfo, "$.deliveryDateTemp");
    	
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Date deliveryDate = sdf.parse(date);
    	
    	/*JSONPath.set(orderInfo, "$.deliveryDate", deliveryDate);*/
    	Order order = new Gson().fromJson(orderInfo, Order.class);
    	order.setDeliveryDate(deliveryDate);
    	order.setPaymentState("0");
    	order.setOrderState("0");
    	order.setDistributorId("d37e46fc92294833a68547808f61d074");
    	order.setUserId("3a657ea8ddc745a698d51aeea2183f4d");
    	int code = (int) ((Math.random() + 1)*1000000000);
    	order.setOrderCode(String.valueOf(code));
    	orderService.save(order);
    	
    	List<OrderProduct> productList = (List<OrderProduct>) JSONPath.read(orderInfo, "$.productList");
    	List<OrderProduct> orderProductList = JSONArray.parseArray(productList.toString(), OrderProduct.class);
    	for (OrderProduct orderProduct : orderProductList) {
    		orderProduct.setOrderId(order.getId());
    		orderProductService.save(orderProduct);
		}
    	return Result.success(order);
    }
    
    @RequestMapping("/goPayRecord")
    public String goPayRecord(){
    	return "bussiness/orderlang/customer/pay_record";
    }
    
    @RequestMapping(value = "/orderReport", method = RequestMethod.POST)
    @ResponseBody
    public Result findOrderReportByCondition(String customerType,String startTime,String endTime) throws Exception {
    	// 订单列表
    	List<OrderReportVO> orderReportList = orderService.findOrderReportByCondition(customerType,startTime,endTime);
    	// 订单统计信息
    	OrderStatisticsVO orderStatisticsVO = orderService.findOrderStatistics(customerType,startTime,endTime);
    	orderStatisticsVO.setOrderReportList(orderReportList);
    	// 退单列表
    	List<RejectReportVO> rejectReportList = rejectService.findRejectReportByCondition(customerType,startTime,endTime);
    	// 退单统计信息
    	RejectStatisticsVO rejectStatisticsVO = rejectService.findRejectStatistics(customerType,startTime,endTime);
    	rejectStatisticsVO.setRejectReportList(rejectReportList);
    	Map<Object, Object> map = new HashMap<Object, Object>();
    	map.put("orderStatisticsVO", orderStatisticsVO);
    	map.put("rejectStatisticsVO", rejectStatisticsVO);
		
    	return Result.success(map);
    	
    }

    /**
     * 根据ID查询单条数据
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:select")
    @RequestMapping(value = "/data/{id}")
    @ResponseBody
    public Object data(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, @PathVariable String id)
            throws Exception {
        Order order = orderService.findOne(id);
        return order;
    }

    /**
     * 根据ID查询单条数据并返回相应表单
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:view")
    @RequestMapping(value = "/form/{page}/{id}")
    public ModelAndView form(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            @PathVariable String page, @PathVariable String id) throws Exception {
        Order order = orderService.findOne(id);
        modelMap.put("order", order);
        return new ModelAndView("bussiness/orderlang/order/" + page, modelMap);
    }

    /**
     * 获取列表展示数据
     * 
     * @param modelMap
     * @param order
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:select")
    @RequestMapping(value = "/list/data", method = RequestMethod.POST)
    @ResponseBody
    public Object listData(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Order order)
            throws Exception {
        List<Order> orderList = orderService.findList(order);
        int total = orderService.findTotal(order);
        EasyUIDataGrid eudg = new EasyUIDataGrid();
        eudg.setTotal(String.valueOf(total));
        eudg.setRows(orderList);
        return eudg;
    }

    /**
     * 获取列表展示数据带分页器用于jsp自己做分页
     * 
     * @param modelMap
     * @param order
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:view")
    @RequestMapping(value = "/list/page", method = RequestMethod.POST)
    @ResponseBody
    public Object listPage(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Order order)
            throws Exception {
        List<Order> orderList = orderService.findList(order);
        int total = orderService.findTotal(order);
        Page<Order> page = new Page<Order>(order.getPage(), order.getRows(), total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", orderList);
        dataMap.put("page", page);
        return dataMap;
    }

    /**
     * 获取所有数据
     * 
     * @param modelMap
     * @param order
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:select")
    @RequestMapping(value = "/list/all", method = RequestMethod.POST)
    @ResponseBody
    public Object listAll(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Order order)
            throws Exception {
        List<Order> orderList = orderService.findAll(order);
        return orderList;
    }

    /**
     * 保存新增的数据
     * 
     * @param modelMap
     * @param order
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:insert")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Order order)
            throws Exception {
        if (!beanValidator(modelMap, order)) {
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        orderService.save(order);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 保存修改的数据
     * 
     * @param modelMap
     * @param order
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public String update(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Order order)
            throws Exception {
        if (!beanValidator(modelMap, order)) {
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        orderService.update(order);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 删除数据库
     * 
     * @param modelMap
     * @param orderId
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, String id)
            throws Exception {
        List<String> listId = Arrays.asList(id.split(","));
        orderService.delete(listId);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 假删除
     * 
     * @param modelMap
     * @param order
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:delete")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public String remove(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Order order)
            throws Exception {
        orderService.remove(order);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 导出Excel数据
     * 
     * @param modelMap
     * @param order
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("orderlang:order:export")
    @RequestMapping(value = "/export")
    public String export(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Order order)
            throws Exception {
        String fileName = DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        List<Order> orderList = orderService.findAll(order);
        new ExportExcel(null, Order.class).setDataList(orderList).write(response, fileName).dispose();
        return null;
    }
}